package client.comm.commlib.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders

abstract class LazyFragment<V : ViewDataBinding, VM : BaseAppViewModel> : Fragment() {
    lateinit var context: BaseActivity<*, *>
    var binding: V? = null
    lateinit var viewModel: VM
    var rootView: View? = null
    var firstLoad = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context = activity as BaseActivity<*, *>
        if (arguments != null) {
            onBundle(arguments!!)
        }
        viewModel = initViewModel()

    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = setContentView(inflater, getViewId())
        view?.apply {
            binding = DataBindingUtil.bind(view.rootView)
        }
        binding?.lifecycleOwner = this

        return view
    }

    override fun onResume() {//和activity的onResume绑定，Fragment初始化的时候必调用，但切换fragment的hide和visible的时候可能不会调用！
        super.onResume()
        if (firstLoad) {

            observerUI()
            init()
            initListener()
            firstLoad = false
        }

    }


    fun setContentView(inflater: LayoutInflater, resId: Int): View? {
        if (rootView == null) {
            rootView = inflater.inflate(resId, null)
        }
        rootView?.apply {
            rootView.parent?.apply {
                val parent = rootView.parent as ViewGroup
                parent.removeView(rootView)
            }
        }
        return rootView
    }


    abstract fun initViewModel(): VM

    abstract fun getViewId(): Int

    open fun onBundle(bundle: Bundle) {}

    open fun observerUI() {}
    open fun init() {}


    open fun initListener() {}

    inline fun <reified VM : ViewModel> createViewModel(): VM {

//        return ViewModelProviders.of(activity!!).get(VM::class.java)
//        if (activity != null && activity is BaseActivity<*, *>)
//            return (activity as BaseActivity<*, *>).createViewModel<VM>()
//        else
        return activityViewModels<VM> { ViewModelProvider.AndroidViewModelFactory(activity!!.application) }.value
    }

}